from sqlalchemy import create_engine
from urllib.parse import quote as urlquote
import pymysql
import time


class ConnectMysqldb(object):
    '''连接MySQL数据库'''

    def __init__(self, config):
        self.config = config

    def __enter__(self):
        uri = "mysql+pymysql://{user}:{passwd}@{host}:{port}/{db}?charset=utf8".format(
            host=self.config['mysql_host'],
            port=self.config['mysql_port'],
            user=self.config['mysql_user'],
            passwd=urlquote(self.config['mysql_passwd']), db=self.config['mysql_db'])
        try:
            self.engine = create_engine(uri, echo=False)
            print('database connected')
            return (self.engine)
        except:
            print('database connect failed,after 3s retrying connect')
            time.sleep(3)
            self.engine = create_engine(uri, echo=False)

    def __exit__(self, Type, value, traceback):
        self.engine.dispose()
        print('database close')
